package cn.hairui.blog.controller.manage;

import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.model.*;
import cn.hairui.blog.service.*;
import cn.hairui.blog.util.CommUtil;
import cn.hairui.blog.util.DateUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author lihairui
 * @version V1.0
 * @date: 2019/3/5 22:42
 */
@Controller
@RequestMapping("/manage")
public class ArticalManageController {
    @Autowired
    private WebInfoService webInfoService;
    @Autowired
    private ArticalService articalService;
    @Autowired
    private TabMenuService tabMenuService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TopicService topicService;

    //列表页面
    @RequestMapping(value = "page/artical/articalList")
    public String articalList() {
        return "manage/page/artical/articalList";
    }

    //新增页面
    @RequestMapping(value = "page/artical/articalAdd")
    public String articalAdd(Model model) {
        //加载下拉字典
        //首页分类
        List<TabMenu> tabMenuList = tabMenuService.list();
        model.addAttribute("navidDic", tabMenuList);

        List<Category> categoryList = categoryService.list();
        model.addAttribute("categoryDic", categoryList);

        List<Topic> topicList = topicService.list();
        model.addAttribute("topicDic", topicList);

        return "manage/page/artical/articalAdd";
    }

    //修改页面
    @RequestMapping(value = "page/artical/articalUpdate")
    public String articalUpdate(HttpServletRequest request, Model model) {
        int id = Integer.parseInt(request.getParameter("id"));
        //加载下拉字典
        //首页分类
        List<TabMenu> tabMenuList = tabMenuService.list();
        model.addAttribute("navidDic", tabMenuList);

        List<Category> categoryList = categoryService.list();
        model.addAttribute("categoryDic", categoryList);

        List<Topic> topicList = topicService.list();
        model.addAttribute("topicDic", topicList);

        Artical artical = articalService.find(id);
        model.addAttribute("artical", artical);

        return "manage/page/artical/articalUpdate";
    }


    //内容编辑页面
    @RequestMapping(value = "page/artical/articalEdit")
    public String articalEdit(HttpServletRequest request, Model model) {

        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);

        int id = Integer.parseInt(request.getParameter("id"));
        //加载下拉字典


        Artical artical = articalService.find(id);
        model.addAttribute("artical", artical);

        return "manage/page/artical/articalMarkdown";
    }


    //列表数据
    @RequestMapping(value = "page/artical/list")
    @ResponseBody
    public String list(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int pageSize = 15;//默认每页显示15条记录
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("limit"));
        } catch (Exception e) {
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Map> articalList = articalService.listMgr();
        PageInfo<Map> pageInfo = new PageInfo<Map>(articalList);
        map.put("data", articalList);
        map.put("code", 0);
        map.put("count", pageInfo.getTotal());
        return JSONUtils.toJSONString(map);
    }

    //新增数据
    @RequestMapping(value = "page/artical/add")
    @ResponseBody
    public String add(HttpServletRequest request, Artical artical) {
        Map map = new HashMap<Object, Object>();
        //处理专题编号
        if (PubConstant.USELESS_DIC_VALUE.equals(artical.getTopicid())) {
            artical.setTopicid(null);
        }
        //添加创建时间
        artical.setCreatedate(DateUtil.getCurrentDate());

        //背景图片 后期改造
        int i = new Random().nextInt(19) + 1;//1-20随机图片
        String imgPath = i + ".jpg";
        artical.setImgpath(imgPath);

        //初始化点赞次数
        artical.setLikenums(0);
        artical.setDissnums(0);
        //原创文章将转载信息置空
        if (PubConstant.DIC_TYPE_0.equals(artical.getType())) {
            artical.setOriginauthor(null);
            artical.setOriginurl(null);
        }

        if (PubConstant.USELESS_DIC_VALUE.equals(artical.getTopicid())) {
            artical.setTopicid(null);
        }
        int pk = articalService.add(artical);

        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }

    //更新数据
    @RequestMapping(value = "page/artical/update")
    @ResponseBody
    public String update(HttpServletRequest request, Artical artical) {
        Map map = new HashMap<Object, Object>();
        //处理专题编号
        if (PubConstant.USELESS_DIC_VALUE.equals(artical.getTopicid())) {
            artical.setTopicid(null);
        }
        //设置更新时间
        artical.setUpdatedate(DateUtil.getCurrentDate());

        /*//背景图片 后期改造
        int i = new Random().nextInt(19) + 1;//1-20随机图片
        String imgPath = i + ".jpg";
        artical.setImgpath(imgPath);

        //初始化点赞次数
        artical.setLikenums(0);
        artical.setDissnums(0);*/

        //原创文章将转载信息置空
        if (PubConstant.DIC_TYPE_0.equals(artical.getType())) {
            artical.setOriginauthor(null);
            artical.setOriginurl(null);
        }

        if (PubConstant.USELESS_DIC_VALUE.equals(artical.getTopicid())) {
            artical.setTopicid(null);
        }
        articalService.update(artical);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }


    //更新文章内容数据
    @RequestMapping(value = "page/artical/updateContent")
    @ResponseBody
    public String updateContent(HttpServletRequest request, Artical artical) {
        Map map = new HashMap<Object, Object>();
        artical.setUpdatedate(DateUtil.getCurrentDate());
        articalService.updateContent(artical);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }

    @Value("${upload_path}")
    private String uploadPath;

    @Value("${virtual_upload_path}")
    private String virtualUploadPath;

    @RequestMapping("page/artical/uploadImage")
    public @ResponseBody
    Map<String, Object> demo(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String contextName = request.getContextPath();
        String fileName = file.getOriginalFilename();

        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = CommUtil.getUUIDUpperCase() + suffixName;
        File targetPath = new File(uploadPath + PubConstant.ARTICAL_DIR);
        if (!targetPath.exists()) {
            targetPath.mkdirs();
        }
        //保存
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(uploadPath + PubConstant.ARTICAL_DIR + fileName);
            Files.write(path, bytes);
            resultMap.put("success", 1);
            resultMap.put("message", "上传成功！");
            resultMap.put("url", contextName + virtualUploadPath + PubConstant.ARTICAL_DIR + fileName);
        } catch (Exception e) {
            resultMap.put("success", 0);
            resultMap.put("message", "上传失败！");
            e.printStackTrace();
        }
        return resultMap;
    }

    //置顶操作
    @RequestMapping(value = "page/artical/articaltop")
    @ResponseBody
    public String articaltop(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int id = Integer.parseInt(request.getParameter("id"));

        Artical artical = articalService.find(id);
        String flag = "";
        if (PubConstant.SWITCH_ON.equals(artical.getIntop())) {
            //取消置顶
            flag = PubConstant.SWITCH_OFF;

        } else {
            //置顶
            flag = PubConstant.SWITCH_ON;
        }
        articalService.updateIntopSts(id, flag);
        map.put(PubConstant.flag, flag);
        return JSONUtils.toJSONString(map);
    }

    //删除数据
    @RequestMapping(value = "page/artical/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(@Param(value = "id") int id, HttpServletRequest request) {
        Map map = new HashMap();
        //判断权限
        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (userinfo == null || !PubConstant.YES_NO_Y.equals(userinfo.getAdminflag())) {
            //普通用户或者游客 无权限删除文章
            map.put(PubConstant.flag, PubConstant.permissions);
        } else if (PubConstant.YES_NO_Y.equals(userinfo.getAdminflag()) && !PubConstant.YES_NO_Y.equals(userinfo.getSuperUser())) {
            //管理人员 但不是超级用户 可以删除自己名下的内容
            Artical artical = articalService.find(id);
            if (artical != null && userinfo.getUsername().equals(artical.getAuthor())) {
                //删除
                articalService.delete(id);
                map.put(PubConstant.flag, PubConstant.success);

            } else if (artical != null && !userinfo.getUsername().equals(artical.getAuthor())) {
                map.put(PubConstant.flag, PubConstant.permissions);
            } else {
                map.put(PubConstant.flag, PubConstant.failed);
            }

        } else if (PubConstant.YES_NO_Y.equals(userinfo.getAdminflag()) && PubConstant.YES_NO_Y.equals(userinfo.getSuperUser())) {
            //超级用户 无限制
            articalService.delete(id);
            map.put(PubConstant.flag, PubConstant.success);
        }
        return JSONUtils.toJSONString(map);
    }


    //批量删除数据
    @RequestMapping(value = "page/artical/deleteBatch", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String deleteBatch(@Param(value = "ids") int[] ids, HttpServletRequest request) {
        Map map = new HashMap();
        try {
            for (int id : ids) {
                articalService.delete(id);
            }
            map.put(PubConstant.flag, PubConstant.success);
        } catch (Exception e) {
            e.printStackTrace();
            map.put(PubConstant.flag, PubConstant.failed);
        }
        return JSONUtils.toJSONString(map);
    }

}
